# -*- coding: utf-8 -*-
import hashlib
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '91065368': {  # witch 支付宝3.6%（10---2w），快捷1.8%（100---5千），qq1.6%（10---5千）
        'API_KEY': '09370acc46315f7b44b33a51e832f18b',
        'gateway': 'http://www.careypay.net/trade/careypay?order_no={}&amount={}&device={}&sign={}&notify_url={}&app_id={}&return_url={}&merchant={}&goods={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


# app_id=xx&amount=xx&order_no=xx&device=xx&app_secret=xx&notify_url=xx
def generate_sign(d, key):
    s = 'app_id={}&amount={}&order_no={}&device={}&app_secret={}&notify_url={}'.format(
        d['app_id'], d['amount'], d['order_no'], d['device'], key, d['notify_url'])
    _LOGGER.info("kairuipay sign str: %s", s)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# status=xx&amount=xx&order_no=xx&order_status=xx&pay_time=xx&app_secret=xx
def generate_notify_sign(d, key):
    s = 'status={}&amount={}&order_no={}&order_status={}&pay_time={}&app_secret={}'.format(
        d['status'], d['amount'], d['order_no'], d['order_status'], d['pay_time'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    return m.hexdigest()


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("kairuipay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    d = OrderedDict((
        ('app_id', app_id),
        ('amount', str(int(pay_amount * 100))),
        ('order_no', str(pay.id)),
        ('device', 'wp'),
        ('notify_url', '{}/pay/api/{}/kairuipay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url', '{}/pay/api/{}/kairuipay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('merchant', 'justpay'),
        ('goods', 'charge'),
    ))
    d['sign'] = generate_sign(d, api_key)
    url = _get_gateway(app_id).format(d['order_no'], d['amount'], d['device'], d['sign'],
                                      d['notify_url'], d['app_id'], d['return_url'], d['merchant'], d['goods'])
    _LOGGER.info("kairuipay create charge data: %s ", url)
    return {'charge_info': url}


# success 
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("kairuipay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['order_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('kairuipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['order_status'])
    trade_no = ''
    total_fee = float(data['amount']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 'success':
        _LOGGER.info('kairuipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pass
